<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px"
        >
          <el-form-item label="员工姓名" prop="userName">
            <el-input
                v-model="queryParams.staffName"
                placeholder="请输入员工姓名"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="用户名" prop="userName">
            <el-input
                v-model="queryParams.userName"
                placeholder="请输入用户名"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="角色" prop="roleId">
            <el-select v-model="queryParams.roleId" placeholder="请选择角色">
              <el-option
                  v-for="item in roleOptions"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
                v-model="dateRange"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate()"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete()"
            >删除
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="用户名" align="center" key="userName" prop="userName" v-if="columns[0].visible"
                           show-overflow-tooltip
          />
          <el-table-column label="员工姓名" align="center" key="staffName" prop="staffName" v-if="columns[1].visible"
                           show-overflow-tooltip
          />
          <el-table-column label="角色" align="center" key="roleName" prop="roleName" v-if="columns[2].visible"
                           show-overflow-tooltip
          />
          <el-table-column label="描述" align="center" key="description" prop="description" v-if="columns[3].visible"
                           show-overflow-tooltip
          />
          <el-table-column label="创建时间" align="center" key="lastLoginTime" prop="lastLoginTime"
                           v-if="columns[4].visible" width="160"
          >
          </el-table-column>
          <el-table-column
              label="操作"
              align="center"
              width="160"
              class-name="small-padding fixed-width"
          >
            <template slot-scope="{row}">
              <el-button
                  size="mini"
                  type="text"
                  @click="handleUpdate(row)"
              >修改
              </el-button>
              <el-button
                  size="mini"
                  type="text"
                  @click="bindEmployees(row)"
              >绑定员工
              </el-button>
              <el-button
                  size="mini"
                  type="text"
                  @click="handleDelete(row)"
              >删除
              </el-button>
            </template>

          </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.curPage"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名" maxlength="20"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入密码" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!--          <el-col :span="12">
                      <el-form-item label="员工姓名" prop="staffName">
                        <el-input v-model="form.staffName" placeholder="请输入员工姓名" maxlength="30"/>
                      </el-form-item>
                    </el-col>-->
          <el-col :span="12">
            <el-form-item label="角色" prop="roleId">
              <el-select v-model="form.roleId" placeholder="请选择角色">
                <el-option
                    v-for="item in roleOptions"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述">
              <el-input v-model="form.description" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <select-employees :open-employees.sync="openEmployees" :id="currentItem.staffId"
                      @submitFormEmployees="submitFormEmployees"
    ></select-employees>
  </div>
</template>

<script>
import { addUser, delUser, listUser, setBindEmploy, updateUser } from '@/api/system/user'
import { listRole } from '@/api/system/role'
import { getToken } from '@/utils/auth'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import SelectEmployees from '@/views/system/user/components/selectEmployees.vue'

export default {
  name: 'User',
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  components: { SelectEmployees, Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      selectUsers: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: void 0,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: void 0,
      // 默认密码
      initPassword: void 0,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/system/user/importData'
      },
      // 查询参数
      queryParams: {
        curPage: 1,
        pageSize: 10,
        staffName: void 0,
        userName: void 0,
        roleId: void 0
      },
      // 列信息
      columns: [
        { key: 0, label: `用户名`, visible: true },
        { key: 1, label: `员工姓名`, visible: true },
        { key: 2, label: `角色`, visible: true },
        { key: 3, label: `描述`, visible: true },
        { key: 4, label: `创建时间`, visible: true }
      ],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '用户名长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        staffName: [
          { required: true, message: '员工姓名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '用户密码不能为空', trigger: 'blur' },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
          { pattern: /^[^<>"'|\\]+$/, message: '不能包含非法字符：< > " \' \\\ |', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '角色不能为空', trigger: 'change' }
        ]
      },
      openEmployees: false,
      employeesList: [],
      currentItem: {}
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getRoleList()
    // this.getDeptTree();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true
      listUser({
        ...this.queryParams,
        startTime: this.dateRange[0],
        endTime: this.dateRange[1]
      }).then(response => {
            this.userList = response.data.records
            this.total = response.data.total
            this.loading = false
          }
      )
    },
    /**查询角色列表*/
    getRoleList() {
      listRole().then(res => {
        this.roleOptions = res.data.records
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        userId: void 0,
        userName: void 0,
        password: void 0,
        staffName: void 0,
        roleId: void 0,
        description: void 0
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.curPage = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.queryParams.deptId = void 0
      this.$refs.tree.setCurrentKey(null)
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.selectUsers = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加用户'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      row = row ? row : this.selectUsers[0]
      row = JSON.parse(JSON.stringify(row))
      this.form = row
      this.open = true
      this.title = '修改用户'
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.userId) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row ? [row.userId] : this.ids
      this.$modal.confirm('是否确认删除用户？').then(function() {
        return delUser( userIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    bindEmployees(row) {
      this.currentItem = row
      this.openEmployees = true
    },
    submitFormEmployees(v) {

      setBindEmploy({
        'staffId': v,
        'userId': this.currentItem.userId
      }).then(res => {
        this.$message.success('绑定成功')
        this.getList()
      })
      this.currentItem = {}
    }
  }
}
</script>
